package com.example.singing.util;

import com.example.singing.manager.SystemConfigManager;
import com.example.singing.model.SystemConfig;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

/**
 * 主题管理器
 * 负责动态切换系统主题和颜色方案
 */
public class ThemeManager {
    private static ThemeManager instance;
    private SystemConfigManager configManager;
    private SystemConfig config;
    
    private ThemeManager() {
        this.configManager = new SystemConfigManager();
        this.config = configManager.getConfig();
    }
    
    public static ThemeManager getInstance() {
        if (instance == null) {
            instance = new ThemeManager();
        }
        return instance;
    }
    
    /**
     * 获取透明度颜色
     */
    private String getTransparentColor(String color) {
        if (color != null && color.startsWith("#") && color.length() == 7) {
            return color + "22";  // 添加透明度
        }
        return color;
    }
    
    /**
     * 应用主题到场景
     */
    public void applyTheme(Scene scene) {
        if (scene == null) return;
        
        String theme = config.getTheme();
        String primaryColor = config.getPrimaryColor();
        String accentColor = config.getAccentColor();
        
        // 根据主题设置背景色
        String backgroundColor;
        String textColor;
        String cardBackgroundColor;
        String borderColor;
        
        if ("dark".equals(theme)) {
            backgroundColor = "#2c3e50";
            textColor = "#ecf0f1";
            cardBackgroundColor = "#34495e";
            borderColor = "#4a5f7a";
        } else {
            backgroundColor = "#f5f5f5";
            textColor = "#2c3e50";
            cardBackgroundColor = "#ffffff";
            borderColor = "#e0e0e0";
        }
        
        // 创建更完整的CSS样式字符串
        String css = String.format(
            ".root { " +
            "-fx-base: %s; " +
            "-fx-background: %s; " +
            "-fx-control-inner-background: %s; " +
            "-fx-text-fill: %s; " +
            "-fx-accent: %s; " +
            "-fx-default-button: %s; " +
            "-fx-focus-color: %s; " +
            "-fx-faint-focus-color: %s; " +
            "} " +
            ".button { " +
            "-fx-background-color: %s; " +
            "-fx-text-fill: white; " +
            "-fx-background-radius: 5px; " +
            "-fx-border-radius: 5px; " +
            "} " +
            ".button:hover { " +
            "-fx-background-color: %s; " +
            "} " +
            ".button:pressed { " +
            "-fx-background-color: %s; " +
            "} " +
            ".tab { " +
            "-fx-background-color: %s; " +
            "-fx-text-fill: %s; " +
            "-fx-background-radius: 5px 5px 0 0; " +
            "} " +
            ".tab:selected { " +
            "-fx-background-color: %s; " +
            "-fx-text-fill: white; " +
            "} " +
            ".tab:hover { " +
            "-fx-background-color: %s; " +
            "} " +
            ".text-field { " +
            "-fx-background-color: %s; " +
            "-fx-text-fill: %s; " +
            "-fx-border-color: %s; " +
            "-fx-border-radius: 3px; " +
            "} " +
            ".text-field:focused { " +
            "-fx-border-color: %s; " +
            "} " +
            ".label { " +
            "-fx-text-fill: %s; " +
            "} " +
            ".color-picker { " +
            "-fx-background-color: %s; " +
            "} " +
            ".color-picker .color-picker-label { " +
            "-fx-background-color: %s; " +
            "}",
            primaryColor, backgroundColor, cardBackgroundColor, textColor,
            accentColor, primaryColor, accentColor, getTransparentColor(accentColor),
            primaryColor, accentColor, primaryColor,
            cardBackgroundColor, textColor, accentColor, accentColor,
            cardBackgroundColor, textColor, borderColor, accentColor, textColor,
            cardBackgroundColor, primaryColor
        );
        
        // 清除现有样式并应用新样式
        scene.getStylesheets().clear();
        scene.getRoot().getStyleClass().clear();
        scene.getRoot().getStyleClass().add("root");
        
        // 使用临时文件方式应用CSS（更可靠）
        try {
            java.io.File tempFile = java.io.File.createTempFile("theme", ".css");
            java.nio.file.Files.write(tempFile.toPath(), css.getBytes("UTF-8"));
            scene.getStylesheets().add("file:///" + tempFile.getAbsolutePath().replace("\\", "/"));
            
            // 延迟删除临时文件
            java.util.Timer timer = new java.util.Timer();
            timer.schedule(new java.util.TimerTask() {
                @Override
                public void run() {
                    tempFile.delete();
                }
            }, 5000); // 5秒后删除
        } catch (Exception e) {
            // 如果文件方式失败，使用data URI方式
            try {
                scene.getStylesheets().add("data:text/css;charset=utf-8," + java.net.URLEncoder.encode(css, "UTF-8"));
            } catch (Exception ex) {
                System.err.println("应用CSS样式失败: " + ex.getMessage());
            }
        }
        
        // 应用特定组件样式
        applyComponentStyles(scene);
    }
    
    /**
     * 应用组件特定样式
     */
    private void applyComponentStyles(Scene scene) {
        String theme = config.getTheme();
        String primaryColor = config.getPrimaryColor();
        String accentColor = config.getAccentColor();
        
        // 按钮样式
        String buttonStyle = String.format(
            "-fx-background-color: %s; " +
            "-fx-text-fill: white; " +
            "-fx-background-radius: 5px; " +
            "-fx-border-radius: 5px; " +
            "-fx-padding: 8 16; " +
            "-fx-font-weight: bold;",
            primaryColor
        );
        
        // 卡片样式
        String cardStyle = String.format(
            "-fx-background-color: %s; " +
            "-fx-background-radius: 10px; " +
            "-fx-border-color: %s; " +
            "-fx-border-width: 1px; " +
            "-fx-border-radius: 10px; " +
            "-fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);",
            theme.equals("dark") ? "#34495e" : "#ffffff",
            theme.equals("dark") ? "#4a5f7a" : "#e0e0e0"
        );
        
        // 标题样式
        String titleStyle = String.format(
            "-fx-font-size: 24px; " +
            "-fx-font-weight: bold; " +
            "-fx-text-fill: %s;",
            theme.equals("dark") ? "#ecf0f1" : "#2c3e50"
        );
        
        // 副标题样式
        String subtitleStyle = String.format(
            "-fx-font-size: 14px; " +
            "-fx-text-fill: %s;",
            theme.equals("dark") ? "#bdc3c7" : "#7f8c8d"
        );
        
        // 递归应用样式到所有节点
        applyStylesRecursively(scene.getRoot(), buttonStyle, cardStyle, titleStyle, subtitleStyle);
    }
    
    /**
     * 递归应用样式到节点及其子节点
     */
    private void applyStylesRecursively(javafx.scene.Node node, String buttonStyle, 
                                      String cardStyle, String titleStyle, String subtitleStyle) {
        if (node == null) return;
        
        // 根据节点类型应用不同样式
        if (node instanceof Button) {
            Button button = (Button) node;
            if (button.getStyleClass().contains("primary") || 
                button.getText().contains("保存") || 
                button.getText().contains("确定") ||
                button.getText().contains("创建")) {
                button.setStyle(buttonStyle);
            }
        } else if (node instanceof VBox || node instanceof HBox) {
            // 检查是否是卡片容器
            if (node.getStyleClass().contains("card") || 
                node.getStyle().contains("background-radius")) {
                node.setStyle(cardStyle);
            }
        } else if (node instanceof Label) {
            Label label = (Label) node;
            if (label.getStyleClass().contains("title") || 
                label.getStyle().contains("font-size: 20") ||
                label.getStyle().contains("font-size: 24") ||
                label.getStyle().contains("font-size: 28")) {
                label.setStyle(titleStyle);
            } else if (label.getStyleClass().contains("subtitle") ||
                      label.getStyle().contains("font-size: 12") ||
                      label.getStyle().contains("font-size: 14")) {
                label.setStyle(subtitleStyle);
            }
        }
        
        // 递归处理子节点
        if (node instanceof javafx.scene.Parent) {
            javafx.scene.Parent parent = (javafx.scene.Parent) node;
            for (javafx.scene.Node child : parent.getChildrenUnmodifiable()) {
                applyStylesRecursively(child, buttonStyle, cardStyle, titleStyle, subtitleStyle);
            }
        }
    }
    
    /**
     * 更新主题配置
     */
    public void updateTheme(String theme, String primaryColor, String accentColor) {
        config.setTheme(theme);
        config.setPrimaryColor(primaryColor);
        config.setAccentColor(accentColor);
        configManager.saveConfig();
    }
    
    /**
     * 获取当前主题
     */
    public String getCurrentTheme() {
        return config.getTheme();
    }
    
    /**
     * 获取主色调
     */
    public String getPrimaryColor() {
        return config.getPrimaryColor();
    }
    
    /**
     * 获取强调色
     */
    public String getAccentColor() {
        return config.getAccentColor();
    }
    
    /**
     * 切换主题
     */
    public void toggleTheme() {
        String currentTheme = config.getTheme();
        String newTheme = "light".equals(currentTheme) ? "dark" : "light";
        config.setTheme(newTheme);
        configManager.saveConfig();
    }
    
    /**
     * 应用动画效果
     */
    public void applyAnimationEffects(javafx.scene.Node node) {
        if (!config.isEnableAnimations()) return;
        
        // 添加淡入效果
        node.setOpacity(0);
        javafx.animation.FadeTransition fadeIn = new javafx.animation.FadeTransition(
            javafx.util.Duration.millis(300), node);
        fadeIn.setFromValue(0);
        fadeIn.setToValue(1);
        fadeIn.play();
        
        // 添加缩放效果
        javafx.animation.ScaleTransition scaleIn = new javafx.animation.ScaleTransition(
            javafx.util.Duration.millis(300), node);
        scaleIn.setFromX(0.9);
        scaleIn.setFromY(0.9);
        scaleIn.setToX(1.0);
        scaleIn.setToY(1.0);
        scaleIn.play();
    }
    
    /**
     * 播放音效
     */
    public void playSoundEffect(String effectType) {
        if (!config.isEnableSoundEffects()) return;
        
        // 这里可以添加音效播放逻辑
        // 由于JavaFX的音效支持有限，这里只是占位符
        System.out.println("播放音效: " + effectType);
    }
    
    /**
     * 获取主题相关的CSS样式
     */
    public String getThemeCSS() {
        String theme = config.getTheme();
        String primaryColor = config.getPrimaryColor();
        String accentColor = config.getAccentColor();
        
        if ("dark".equals(theme)) {
            return String.format(
                ".root { -fx-base: %s; -fx-background: #2c3e50; -fx-control-inner-background: #34495e; } " +
                ".button { -fx-background-color: %s; -fx-text-fill: white; } " +
                ".button:hover { -fx-background-color: %s; } " +
                ".text-field { -fx-background-color: #34495e; -fx-text-fill: #ecf0f1; } " +
                ".label { -fx-text-fill: #ecf0f1; } " +
                ".tab { -fx-background-color: #34495e; -fx-text-fill: #ecf0f1; } " +
                ".tab:selected { -fx-background-color: %s; }",
                primaryColor, primaryColor, accentColor, accentColor
            );
        } else {
            return String.format(
                ".root { -fx-base: %s; -fx-background: #f5f5f5; -fx-control-inner-background: #ffffff; } " +
                ".button { -fx-background-color: %s; -fx-text-fill: white; } " +
                ".button:hover { -fx-background-color: %s; } " +
                ".text-field { -fx-background-color: #ffffff; -fx-text-fill: #2c3e50; } " +
                ".label { -fx-text-fill: #2c3e50; } " +
                ".tab { -fx-background-color: #ffffff; -fx-text-fill: #2c3e50; } " +
                ".tab:selected { -fx-background-color: %s; }",
                primaryColor, primaryColor, accentColor, accentColor
            );
        }
    }
}
